package net.adetech.cjg.outerservice.controller;

import com.alibaba.fastjson.JSONObject;
import net.adetech.cjg.outerservice.service.BaseService;
import net.adetech.cjg.outerservice.utils.ApplicationContextProvider;
import net.adetech.cjg.outerservice.utils.OuterServiceUtil;
import net.adetech.framework.entity.ServiceRequest;
import net.adetech.framework.entity.ServiceResponse;
import net.adetech.framework.utils.SerializeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class OuterServiceController {

    @Autowired
    OuterServiceUtil outerServiceUtil;

    @Autowired
    ApplicationContextProvider provider;

    @RequestMapping("/cjg/demo")
    public String demo(int a,int b)
    {

        ServiceRequest request = new ServiceRequest();
        Map<String,Object> params = new HashMap<>();
        params.put("a",a);
        params.put("b",b);
        request.setServiceName("cjg.demo");
        request.setParams(params);
        ServiceResponse response = outerServiceUtil.call(request);

        return JSONObject.toJSONString(response.getResults());
    }

    @RequestMapping("/cjg/callOut")
    public String callOut(String data)
    {
        ServiceResponse response = new ServiceResponse();
        try {
            ServiceRequest request = (ServiceRequest) SerializeUtil.stringToObject(data);
            BaseService service = provider.getServiceBean(request.getServiceName());
            Map<String,Object> resultMap = service.invoke(request.getParams());
            response.setResults(resultMap);
        }catch (Exception e)
        {
            e.printStackTrace();
            response.setState("ERROR");
            response.setMsg(e.getMessage());
        }
        String result = SerializeUtil.objectToString(response);
        return "{result:'"+result+"'}";
    }
}
